// subpages/pages/addCategory/addCategory.js
import { getCategoryList, editCategory, addCategory, delCategory } from '../../../services/category/index';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dataList: [],
    visible: false,
    name: '',
    ort: '',
    kid: '',
    isEdit: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getList();
  },
  // 获取数据
  getList() {
    getCategoryList({}).then((res) => {
      this.setData({
        dataList: res.data,
      });
    });
  },
  edit(e) {
    const { item } = e.target.dataset;
    this.setData({
      visible: true,
      kid: item.kid,
      name: item.classifyName,
      ort: item.sortNo,
      isEdit: true,
    });
  },
  del(e) {
    const { item } = e.target.dataset;
    delCategory({
      kid: item.kid,
    }).then((res) => {
      wx.showToast({
        title: '删除成功',
        icon: 'none',
        duration: 1000,
      });
      setTimeout(() => {
        this.closeDialog();
        this.getList();
      }, 200);
    });
  },
  getname(e) {
    const { value } = e.detail;
    this.setData({
      name: value,
    });
  },
  getort(e) {
    const { value } = e.detail;
    this.setData({
      ort: value,
    });
  },
  getkid(e) {
    const { value } = e.detail;
    this.setData({
      kid: value,
    });
  },
  closeDialog() {
    this.setData({
      visible: false,
      name: '',
      ort: '',
      kid: '',
      isEdit: false,
    });
    this.getList();
  },
  confirmDialog() {
    const { name, ort, kid, isEdit } = this.data;
    if (isEdit) {
      editCategory({
        kid: kid,
        classifyName: name,
        sortNo: ort,
      })
        .then((res) => {
          this.closeDialog();
        })
        .catch((err) => {
          this.closeDialog();
        });
    } else {
      addCategory({
        kid,
        classifyName: name,
        sortNo: ort,
      })
        .then((res) => {
          if (res.status) {
            wx.showToast({
              title: '新增成功',
              icon: 'none',
              duration: 1000,
            });
            setTimeout(() => {
              this.closeDialog();
              this.getList();
            }, 200);
          }
        })
        .catch((err) => {
          this.closeDialog();
          this.getList();
        });
    }
  },
  handleClick() {
    this.setData({
      visible: true,
      isEdit: false,
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  formSubmit() {
    wx.navigateBack({
      delta: 1,
    });
  },
});
